package com.minelx.woods.server.common;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Date;

import static io.jsonwebtoken.SignatureAlgorithm.HS256;

// FIXME 2021/9/15  THIS METHOD NEEDED TEST SUPPORT!
public class JWToken {

	public static final String ID = "1";

	public static final long EXPIATED_AFTER = 1000 * 60 * 60;

	public static final SecretKey SECRET_KEY = serverSecretKey();

	public static String create(String subject) {
		long now = System.currentTimeMillis();
		JwtBuilder builder = Jwts.builder()
				.setId(ID)
				.setSubject(subject)
				.setIssuer("user")
				.setIssuedAt(new Date(now))
				.signWith(HS256, SECRET_KEY);
		builder.setExpiration(new Date(now + EXPIATED_AFTER));
		return builder.compact();
	}

	public static Claims parse(String tokenAsText) {
		return Jwts.parser()
				.setSigningKey(SECRET_KEY)
				.parseClaimsJws(tokenAsText)
				.getBody();
	}

	public static SecretKey serverSecretKey() {
		byte[] encodedKey = Base64.encode("WOODS_SECRET_KEY".getBytes(StandardCharsets.UTF_8));
		return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
	}
}
